#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using KLib.Graphics;

using System.IO;
#endregion

namespace KLib.Scene
{
    /// <summary>
    /// The SceneGraph is a collection of self-updating/drawing SceneLayers, which in turn contain self-updating/drawing SceneNodes.
    /// Adding Layers and Nodes to the SceneGraph helps to organize game objects, and make sure everything is updated and drawn as required.
    /// </summary>
    [RegistersService(typeof(ISceneGraphService))]
    public class SceneGraph : KLib.DrawableGameComponent, ISceneGraphService
    {
        #region Fields
        private List<SceneLayer> layers;
        private List<SceneNode> nodes;

        private List<SceneNode> allNodes;

        [RequiredService]
        private SpriteRenderer spriteBatch;
        private Camera.CameraManager camera;
        #endregion

        #region Properties
        public IList<SceneLayer> Layers
        {
            get { return layers; }
        }

        public IList<SceneNode> AllNodes
        {
            get { return allNodes; }
        }
        #endregion

        #region Events
        public delegate void SceneNodeEventArgs(SceneLayer layer, SceneNode node);
        public delegate void SceneLayerEventArgs(SceneGraph sceneGraph, SceneLayer layer);

        public event SceneNodeEventArgs NodeAdded;
        public event SceneNodeEventArgs NodeRemoved;

        public event SceneLayerEventArgs LayerAdded;
        public event SceneLayerEventArgs LayerRemoved;
        #endregion

        #region Initialization

        /// <summary>
        /// Creates a new SceneGraph with no Layers or Nodes
        /// </summary>
        /// <param name="game"></param>
        public SceneGraph(Game game)
            : base(game)
        {
            camera = (Camera.CameraManager)game.Services.GetService(typeof(Camera.ICameraManagerService));
        }

        public override void Initialize()
        {
            base.Initialize();
            // TODO: Add your initialization code here
            spriteBatch = new SpriteRenderer(GraphicsDevice, Game);
            layers = new List<SceneLayer>();
            nodes = new List<SceneNode>();
            allNodes = new List<SceneNode>();
        }

        protected override void LoadContent()
        {
            base.LoadContent();
        }

        #endregion

        #region Methods
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            foreach (SceneLayer layer in layers)
            {
                if (layer.Enabled)
                  layer.Update(gameTime);
            }
        }

        public override void Draw(GameTime gameTime)
        {
            spriteBatch.camera = camera.CurrentCamera;
            spriteBatch.Begin();
            foreach (SceneLayer layer in layers)
            {
                if (layer.Visible)
                    layer.Draw(spriteBatch);
            }
            spriteBatch.End();
            base.Draw(gameTime);
        }

        #region Layer Management
        /// <summary>
        /// Adds a SceneLayer to the SceneGraph. Each frame it is traversed and all its SceneNodes are updated/drawn.
        /// </summary>
        /// <param name="layer">The SceneLayer to add.</param>
        public void AddLayer(SceneLayer layer)
        {
            if (layers.Contains(layer)) return;
            layer.SceneGraph = this;
            layers.Add(layer);
            layers.Sort();

            layer.NodeAdded += new SceneNodeEventArgs(NodeAddedHandler);

            if (LayerAdded != null)
                LayerAdded(this, layer);
        }

        /// <summary>
        /// Removes a SceneLayer to the SceneGraph. It is only removed from the SceneGraph, it is NOT Disposed.
        /// </summary>
        /// <param name="layer">The layer to be removed.</param>
        public void RemoveLayer(SceneLayer layer)
        {
            layers.Remove(layer);

            if (LayerRemoved != null)
                LayerRemoved(this, layer);
        }

        public void DisposeLayer(SceneLayer layer)
        {
           layers.Remove(layer);

            if (LayerRemoved != null)
                LayerRemoved(this, layer);
            layer = null;
            layer.Dispose();
        }
        #endregion

        #region Node Management
        /// <summary>
        /// Adds a SceneNode directly to the SceneGraph. This should only be used for SceneNodes that are not constrianed to a layer. (E.g. a Camera, Managers).
        /// If the SceneNode should be constrianed to a layer, use layer.AddNode() instead.
        /// </summary>
        /// <param name="node">The Node to be Added</param>
        public void AddNode(SceneNode node)
        {
            if (nodes.Contains(node)) return;
            nodes.Add(node);

            if (NodeAdded != null)
                NodeAdded(null, node);
        }

        /// <summary>
        /// Removes a SceneNode from the SceneGraph. The node is not deleted, it is simply no longer attached to the SceneGraph.
        /// </summary>
        /// <param name="node">The Node to be Removed</param>
        /// <returns>True if the Removal was sucessful</returns>
        public bool RemoveNode(SceneNode node)
        {
            if (NodeRemoved != null)
                NodeRemoved(null, node);

            return nodes.Remove(node);
        }

        #endregion

        #endregion

        #region Helper Methods

        #endregion

        #region Event Handlers
        void NodeAddedHandler(SceneLayer layer, SceneNode node)
        {
            allNodes.Add(node);

            if (NodeAdded != null)
                NodeAdded(layer, node);
        }
        #endregion

        #region Saving/Loading
        public void Save(string fileName)
        {
            BinaryWriter file = new BinaryWriter(File.Open(fileName + ".map", FileMode.Create));

            file.Write(layers.Count);
            for (int l = 0; l < layers.Count; l++)
            {
                file.Write(layers[l].Nodes.Count);
                for (int i = 0; i < layers[l].Nodes.Count; i++)
                {
                    SceneNode<Entities.Entity> enityNode = layers[l].Nodes[i] as SceneNode<Entities.Entity>;
                    if (enityNode != null)
                    {
                        file.Write(enityNode.Object.Name);
                        file.Write(enityNode.Object.Position.X);
                        file.Write(enityNode.Object.Position.Y);
                        file.Write(enityNode.Object.Rotation);
                    }
                    else
                    {
                        file.Write("skip");
                    }
                }
            }
            file.Close();
        }

        public void Load(string fileName, Physics.PhysicsManager physics, MaterialManager materials)
        {
            BinaryReader file = new BinaryReader(File.Open(fileName + ".map", FileMode.Open, FileAccess.Read));
            int layerCount = file.ReadInt32();

            for (int l = 0; l < layerCount; l++)
            {
                int nodeCount = file.ReadInt32();
                for (int i = 0; i < nodeCount; i++)
                {
                    string assetName = file.ReadString();
                    if (assetName == "skip" || string.IsNullOrEmpty(assetName)) continue;

                    KLib.Entities.Entity newEntity = Entities.Entity.Load("data/objects/" + assetName, materials);
                    newEntity.Texture = materials.LoadAndGetTexture(newEntity.TextureName);
                    newEntity.Position = new Vector2(file.ReadSingle(), file.ReadSingle());
                    newEntity.Rotation = file.ReadSingle();
                    physics.AddBody(newEntity.PhysicsBody);
                    this.layers[l].AddNode(new SceneNode<Entities.Entity>(newEntity));
                }
            }
        }
        #endregion
    }
}